//
//  YSRoomListViewController.m
//  Yaoyle
//
//  Created by ZhaoXudong on 14-9-15.
//  Copyright (c) 2014年 ZhaoXudong. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "YSRoomListViewController.h"
#import "YSLoginViewController.h"
#import "YSUserModel.h"
#import "YSRoomModel.h"
#import "YSRoomListCell.h"
#import "YSGlobal.h"
#import "JSONKit.h"
#import "NSData+AES256.h"
#import "YSGameViewController.h"
#import "YSPrizeViewController.h"
#import "YSUserInfoViewController.h"
#import "AsyncSocket.h"
#import "AsyncUdpSocket.h"
#import "YSAppDelegate.h"

@interface YSRoomListViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, GameViewDelegate> {
    __weak IBOutlet UITableView *roomList;
    __weak IBOutlet UITextField *searchTextFiled;
    __weak IBOutlet UIScrollView *contentView;
    
    __weak IBOutlet UILabel *userName;
    
    NSMutableArray *roomListArray;
    NSArray *gameUsersArray;
    
    eSocketAciton socketAction;
    
    NSTimer *timer;
    
    YSRoomModel *selectRoomModel;
    
    __weak IBOutlet UIImageView *headImageView;
    AVAudioPlayer *thePlayer;
}

@property (nonatomic, strong)AsyncSocket *socket1;

@end

@implementation YSRoomListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        roomListArray = [NSMutableArray array];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(login)
                                                     name:kNotificationLoginOut
                                                   object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(showFirstLogin)
                                                     name:kNotificationFirstLogin
                                                   object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [UIImageView roundImage:headImageView];
    
#if TARGET_IPHONE_SIMULATOR
#else
    [self playBackSound];
#endif
}

- (void)viewWillAppear:(BOOL)animated {
    // 启动一个心跳的定时器
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (![YSUserModel isLogin]) {
        if (_userModel) {
            _userModel = nil;
        }
        [self login];
    } else {
        _userModel = [[YSUserModel alloc] init];
        userName.text = _userModel.name;
        if (![YSUtility isBlankObject:_userModel.photoUrl]) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_userModel.photoUrl]];
            headImageView.image = [UIImage imageWithData:data];
        }
        
        [self performSelector:@selector(getGameRoomList)
                   withObject:nil
                   afterDelay:.5];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    // 注销心跳定时器
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showFirstLogin {
    [self showMsgWithTitle:@"提示" msg:@"您今天是第一次进入游戏，赠送您400幸运豆"];
}

- (void)playBackSound {
    NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"game_bg" ofType:@"mp3"];       //创建音乐文件路径
    NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
    
    thePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];

    [thePlayer setVolume:1];   //设置音量大小
    [thePlayer prepareToPlay];
    
    thePlayer.numberOfLoops = -1;//设置音乐播放次数  -1为一直循环
    [thePlayer play];   //播放
}

#pragma mark -

- (void)startSocket {
    if (_socket1 == nil) {
        _socket1 = [[AsyncSocket alloc] initWithDelegate:self];
        
        if (![_socket1 connectToHost:SOCKET_SERVER_URL
                              onPort:SOCKET_SERVER_PORT
                         withTimeout:-1
                               error:nil]) {
            NSLog(@"fail");
        } else {
            NSLog(@"OK");
        }
    }
}

- (void)getGameRoomList {
    
    [roomListArray removeAllObjects];
    [YSProgressHUD showHUDAddedTo:self.view];
    [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_ROOM_LIST
                                              delegate:self
                                                params:@{@"pageNum":@"1"}];
}

- (void)login {
    YSLoginViewController *loginVC = [[YSLoginViewController alloc] initWithNibName:@"YSLoginViewController" bundle:nil];
    loginVC.block = ^(YSUserModel *model) {
        _userModel = model;
        [self.navigationController popToRootViewControllerAnimated:NO];
        [self getGameRoomList];
    };
    [self.navigationController pushViewController:loginVC animated:NO];
}


- (IBAction)userInfoBtnClick:(id)sender {
    YSUserInfoViewController *userInfoVC = [[YSUserInfoViewController alloc] initWithNibName:@"YSUserInfoViewController" bundle:nil];
    userInfoVC.userModel = _userModel;
    [self.navigationController pushViewController:userInfoVC animated:YES];
}

// 抽奖
- (IBAction)raffleBtnClick:(id)sender {
    YSPrizeViewController *prizeVC = [[YSPrizeViewController alloc] initWithNibName:@"YSPrizeViewController" bundle:nil];
    prizeVC.userModel = self.userModel;
    [self.navigationController pushViewController:prizeVC animated:YES];
}

- (IBAction)refreshBtnClick:(id)sender {
    [self getGameRoomList];
}

- (IBAction)searchBtnClick:(id)sender {
    NSString *searchRoomNo = searchTextFiled.text;
    
    if (searchRoomNo.length == 0 || [YSUtility isBlankObject:searchRoomNo]) {
        [self showMsgWithTitle:@"提示" msg:@"请输入要查找的房间号"];
        return;
    }
    [YSProgressHUD showHUDAddedTo:self.view];
    
    [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_SEARCH_ROOM
                                              delegate:self
                                                params:@{@"roomNo":searchRoomNo}];
}

- (IBAction)inRoomBtnClick:(id)sender {
    [self joinRoom];
}

- (void)joinRoom {
    if (selectRoomModel) {
        [YSProgressHUD showHUDAddedTo:self.view];
        NSDictionary *dict = @{@"actionCode":[YSUtility getSocketInterface:eSocketJoinRoom],
                               @"uid":[YSGlobal getUID],
                               @"gamblingId":selectRoomModel.roomId};
        
        NSString *str = [YSUtility encryptSocketDict:dict];
        socketAction = eSocketJoinRoom;
        [_socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    }
}

- (void)joinGameWithRoomModel:(YSRoomModel*)model {
    YSGameViewController *gameVC = [[YSGameViewController alloc] initWithNibName:@"YSGameViewController" bundle:nil];
    gameVC.userModel = self.userModel;
    gameVC.roomModel = model;
    gameVC.socket1 = _socket1;
    if (socketAction == eSocketCreateRoom) {
        gameVC.roomType = eRoomCreate;
        gameVC.playerArray = [NSMutableArray array];
    } else {
        gameVC.roomType = eRoomJoin;
        NSMutableArray *tempArray = [NSMutableArray array];
        NSInteger nIndex = 1;
        for (NSDictionary *d in gameUsersArray) {
            YSUserModel *userModel = [[YSUserModel alloc] initFromUserInfo:d];
            [tempArray addObject:@{@"index":[NSString stringWithFormat:@"%d",nIndex],
                                   @"info" :userModel}];
            nIndex ++;
        }
        gameVC.playerArray = tempArray;
    }
    gameVC.delegate = self;
    gameVC.block = ^(eSocketAciton action) {
        socketAction = action;
    };
    [self.navigationController pushViewController:gameVC animated:YES];
}

- (IBAction)createRoomBtnClick:(id)sender {
    
    socketAction = eSocketCreateRoom;
    
    NSError *error = nil;
    
    if ([_socket1 isConnected]) {
        [self createRoom];
    } else {
        if (![_socket1 connectToHost:SOCKET_SERVER_URL
                             onPort:SOCKET_SERVER_PORT
                        withTimeout:-1
                              error:&error]) {
            NSLog(@"%@",error.userInfo);
        } else {
            NSLog(@"OK");
        }
    }
}

- (void)createRoom {
    // 创建游戏
    [YSProgressHUD showHUDAddedTo:self.view];
    NSDictionary *dict = @{@"actionCode":[YSUtility getSocketInterface:socketAction],
                           @"uid":[YSGlobal getUID]};

    NSString *str = [YSUtility encryptSocketDict:dict];
    
    [_socket1 writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}

- (IBAction)fastBeginBtnClick:(id)sender {
    int nIndex = 0;
    
    for (YSRoomModel *model in roomListArray) {
        if ([model isWaitGame] && ![model isMaxNum]) {
            // 进入房间
            socketAction = eSocketJoinRoom;
            selectRoomModel = model;
            [self joinRoom];
            break;
        }
    }
    
    if (nIndex >= roomListArray.count) {
        // 创建房间
        socketAction = eSocketCreateRoom;
        [self createRoom];
    }
    
}

#pragma mark - NetWorkDelegate

- (void)didSuccess:(NetworkMgr *)api userInfo:(NSDictionary *)info {
    [YSProgressHUD hideHUDForView:self.view];
    
    NSInteger funId = [info[kFUN_ID] integerValue];
    NSDictionary *re = info[API_Result_RE];
    if ([YSUtility isBlankObject:re]) {
        return;
    }
    
    re = [YSUtility returnDictionary:re];
    if (funId == eAPI_ROOM_LIST) {
        [self startSocket];
        NSArray *array = re[@"roomList"];
        [roomListArray removeAllObjects];
        if ([YSUtility isBlankObject:array] || array.count == 0) {
            [roomList reloadData];
            return;
        }
        
        for (NSDictionary *dict in array) {
            YSRoomModel *model = [[YSRoomModel alloc] initWithDict:dict];
            [roomListArray addObject:model];
        }
        
        [roomList reloadData];
    } else if (funId == eAPI_SEARCH_ROOM) {
        // 查找成功后，直接加入游戏
        socketAction = eSocketJoinRoom;
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [UIView animateWithDuration:.2 animations:^{
        [self.view setFrame:CGRectMake(0, -160, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [UIView animateWithDuration:.2 animations:^{
        [self.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }];
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - UITableViewDelegate + DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return roomListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YSRoomListCell *cell = [[YSRoomListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"roomListCell"];
    [cell setRoomListModel:[roomListArray objectAtIndex:indexPath.row]];

    UIImage *image = [UIImage imageNamed:@"cell_select_bg"];
    
    UIImageView *cellBg = [[UIImageView alloc] initWithImage:image];
    cellBg.frame = cell.selectedBackgroundView.frame;
    
    cell.selectedBackgroundView = cellBg;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    selectRoomModel = [roomListArray objectAtIndex:indexPath.row];
    
    [self joinRoom];
}

#pragma mark - socket

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {
    [YSProgressHUD hideHUDForView:self.view];
    NSLog(@"dis connect");
}

// 连接成功后--调用
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {
    [sock readDataWithTimeout:-1 tag:0];
    
    switch (socketAction) {
        case eSocketCreateRoom:
            [self createRoom];
            break;
        case eSocketJoinRoom:
            ;;
            break;
            
        default:
            break;
    }
}

// 接收数据后--调用
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
    [YSProgressHUD hideHUDForView:self.view];
    
    [sock readDataWithTimeout:-1 tag:0];
    
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    str = [NSData AES256DecryptWithCiphertextExt:str];
    
    if (str == nil) {
        return;
    }
    
    NSError *error;
    NSData *dataJSON = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:dataJSON
                                                                 options:NSJSONReadingMutableLeaves
                                                                   error:&error];

    NSInteger status = [responseDict[@"status"] integerValue];
    
    if (status == 0) {
        // 系统广播来了
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSystemRadio
                                                            object:nil
                                                          userInfo:responseDict];
        return;
    }
   
    if (status != 200) {
        switch (socketAction) {
            case ePlayerReady:
            case ePlayerBegin:
            case ePlayerExit:
            case ePlayerGuess:
            case ePlayerOpen:
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSocketFail
                                                                    object:nil
                                                                  userInfo:responseDict];
                
            default:
                [self showToastMessage:responseDict[@"msg"]];

                break;
        }
        return;
    }
    
    switch (socketAction) {
        case eSocketJoinRoom: {
            NSDictionary *re = responseDict[API_Result_RE];
            gameUsersArray = re[@"gamers"];
            [self joinGameWithRoomModel:selectRoomModel];
        }
            break;
        case eSocketCreateRoom: {
            NSDictionary *re = responseDict[API_Result_RE];
            YSRoomModel * roomModel = [[YSRoomModel alloc] initWithDict:@{RoomNO:re[@"boardNo"],
                                                                          RoomId:re[@"gamblingId"],
                                                                          RoomGamerNum: @"1",
                                                                          RoomMaxGamerNum:  @"5",
                                                                          RoomScore:re[@"score"],
                                                                          RoomStatus:[NSString stringWithFormat:@"%d",eGameWait]}];
            [self joinGameWithRoomModel:roomModel];
        }
            break;
        case ePlayerReady:
        case ePlayerBegin:
        case ePlayerExit:
        case ePlayerGuess:
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationOtherStatus
                                                                object:nil
                                                              userInfo:responseDict];
            break;
        default:
            break;
    }
    
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag {
    [sock readDataWithTimeout:-1 tag:0];
}

#pragma mark - GameViewDelegate
- (void)soundOn {
    [thePlayer play];
}
- (void)soundOff {
    [thePlayer pause];
}
@end
